// 响应式storage
import type { App } from "vue";
import { ref, onMounted, onUnmounted, type Ref } from "vue";
import Storage from "responsive-storage";
import { routerArrays } from "@/layout/types";
import { responsiveStorageNameSpace } from "@/config";

export const injectResponsiveStorage = (app: App, config: PlatformConfigs) => {
  const nameSpace = responsiveStorageNameSpace();
  const configObj = Object.assign(
    {
      // layout模式以及主题
      layout: {
        layout: config.Layout,
        theme: config.Theme,
        darkMode:
          Storage.getData("layout", nameSpace)?.darkMode ?? config.DarkMode,
        sidebarStatus: config.SidebarStatus,
        epThemeColor: config.EpThemeColor,
        themeColor: config.Theme, // 主题色（对应系统配置中的主题色，与theme不同的是它不会受到浅色、深色整体风格切换的影响，只会在手动点击主题色时改变）
        overallStyle: config.OverallStyle // 整体风格（浅色：light、深色：dark、自动：system）
      },
      // 系统配置-界面显示
      configure: {
        grey: config.Grey,
        weak: config.Weak,
        hideTabs: config.HideTabs,
        hideFooter: config.HideFooter,
        showLogo: config.ShowLogo,
        showModel: config.ShowModel,
        multiTagsCache: config.MultiTagsCache,
        stretch: config.Stretch
      }
    },
    config.MultiTagsCache
      ? {
          // 默认显示顶级菜单tag
          tags: Storage.getData("tags", nameSpace) ?? routerArrays
        }
      : {}
  );

  app.use(Storage, { nameSpace, memory: configObj });
};

// 定义 Element Plus 的响应式断点
// 你可以在这里根据需要调整断点值
const breakpoints = {
  xs: 0, // <768px
  sm: 768, // ≥768px
  md: 992, // ≥992px
  lg: 1200, // ≥1200px
  xl: 1920 // ≥1920px
};

// 定义输入对象的类型
type ResponsiveValue = {
  [key in keyof typeof breakpoints]?: number;
};

/**
 * 响应式地根据屏幕尺寸获取对应的值
 * @param values 一个包含不同尺寸键和对应值的对象
 * @returns 一个 ref 对象，其值会随着屏幕尺寸变化而自动更新
 */
export const useResponsiveValue = (
  values: ResponsiveValue,
  onChange?: (value: number | undefined) => void
): Ref<number | undefined> => {
  const responsiveValue = ref<number | undefined>(undefined);

  const calculateValue = () => {
    const width = window.innerWidth;
    let value: number | undefined;

    if (width >= breakpoints.xl && values.xl !== undefined) {
      value = values.xl;
    } else if (width >= breakpoints.lg && values.lg !== undefined) {
      value = values.lg;
    } else if (width >= breakpoints.md && values.md !== undefined) {
      value = values.md;
    } else if (width >= breakpoints.sm && values.sm !== undefined) {
      value = values.sm;
    } else if (values.xs !== undefined) {
      value = values.xs;
    } else {
      value = undefined;
    }

    if (responsiveValue.value !== value) {
      responsiveValue.value = value;
      if (onChange) onChange(value);
    }
  };

  const handleResize = () => {
    calculateValue();
  };

  onMounted(() => {
    calculateValue();
    window.addEventListener("resize", handleResize);
  });

  onUnmounted(() => {
    window.removeEventListener("resize", handleResize);
  });

  return responsiveValue;
};
